<template>
  <div>
    <!-- 操作栏 -->
    <el-card shadow="never" class="mb-5 border-box">
      <el-row justify="space-between" align="middle" :gutter="10">
        <el-col :lg="12" :md="12" :sm="14" :xs="16">
          <div class="flex gap-2">
            <el-input
              v-model="searchVal"
              :prefix-icon="Search"
              clearable
              placeholder="输入展品名称查询"
              class="w-250px!"
              @input="searchExhibitions"
            />
            <el-button type="primary" @click="toAddExhibition">
              <el-icon>
                <Plus />
              </el-icon>
              添加展品
            </el-button>
          </div>
        </el-col>
        <el-col :lg="12" :md="12" :sm="0" :xs="0">
          <div class="custom-segmented flex justify-end">
            <el-radio-group v-model="statusFilter" size="default" @change="filterByStatus">
              <el-radio-button label="showing">展出中</el-radio-button>
              <el-radio-button label="maintenance">维护中</el-radio-button>
              <el-radio-button label="removed">已下架</el-radio-button>
            </el-radio-group>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <div class="page-content exhibition-list">
      <!-- 展品列表 -->
      <div v-if="!showEmpty" class="h-[calc(100vh-310px)] overflow-y-auto">
        <el-row :gutter="20" v-if="!showEmpty" class="overflow-y-auto">
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            v-for="item in exhibitionList"
            :key="item.id"
            class="mb-5"
          >
            <el-card
              :body-style="{ padding: '0px', height: '100%' }"
              shadow="hover"
              class="exhibition-card"
            >
              <!-- 骨架屏 -->
              <el-skeleton animated :loading="isLoading" class="w-full h-full">
                <template #template>
                  <div class="aspect-ratio-16/9"></div>
                  <div class="p-3.5">
                    <el-skeleton-item variant="h3" class="w-4/5" />
                    <div class="flex items-center mt-2">
                      <el-skeleton-item variant="text" class="mr-4" />
                      <el-skeleton-item variant="text" class="w-3/10" />
                    </div>
                    <el-skeleton-item variant="text" class="w-full mt-4" />
                    <el-skeleton-item variant="text" class="w-full mt-2" />
                  </div>
                </template>

                <template #default>
                  <div class="w-full h-full flex flex-col">
                    <el-image
                      v-if="JSON.parse(item.coverImage || '[]').length"
                      class="exhibition-image w-full h-140px object-cover"
                      :src="JSON.parse(item.coverImage || '[]')[0].path"
                      fit="cover"
                    >
                      <template #error>
                        <div
                          class="image-slot flex justify-center items-center w-full h-full bg-fill-light text-text-secondary text-30px"
                        >
                          <el-icon>
                            <Picture />
                          </el-icon>
                        </div>
                      </template>
                    </el-image>

                    <div class="flex-1">
                      <div class="p-3 h-full box-border flex flex-col">
                        <div class="flex justify-between items-start">
                          <h3 class="text-lg font-medium line-clamp-1">{{ item.name }}</h3>
                          <el-tag :type="getStatusType(item.status || 1) as any">
                            {{ statusTextMap[item.status || 1] }}
                          </el-tag>
                        </div>
                        <div class="text-sm text-gray-500 mt-1 flex items-center">
                          <el-icon>
                            <Location />
                          </el-icon>
                          <span class="ml-1 line-clamp-1">{{ item.location }} {{ item.floor }}</span>
                          <span class="ml-3 line-clamp-1">编码：{{ item.itemNumber }}</span>
                        </div>
                        <p
                          class="text-sm text-gray-600 mt-2 line-clamp-2 whitespace-pre-line break-all"
                        >
                          {{ item.description }}
                        </p>
                        <div class="flex justify-end items-center mt-auto pt-1">
                          <div class="action-buttons">
                            <el-button
                              type="primary"
                              text
                              size="small"
                              @click.stop="viewDetail(item)"
                            >
                              <el-icon><View /></el-icon>查看
                            </el-button>
                            <el-button
                              type="primary"
                              text
                              size="small"
                              @click.stop="editExhibition(item)"
                            >
                              <el-icon><Edit /></el-icon>编辑
                            </el-button>
                            <el-button
                              type="danger"
                              text
                              size="small"
                              @click.stop="confirmDelete(item)"
                            >
                              <el-icon><Delete /></el-icon>删除
                            </el-button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
              </el-skeleton>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <!-- 空状态 -->
      <div class="flex justify-center h-[calc(100vh-310px)]" v-if="showEmpty">
        <el-empty description="暂无展品数据" />
      </div>

      <!-- 分页器 -->
      <div class="flex justify-center">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[8, 16, 24, 32]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :hide-on-single-page="false"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { router } from '@/router'
import { Search, Picture, Location, Plus, View, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ExhibitionItemVoduixiang } from '@/api/4a/types'
import {
  scenicExhibitionItemOpenApiDeleteUsingPost,
  scenicExhibitionItemPageUsingPost,
} from '@/api/4a/zhanpinguanli'

// 请求参数
const formData = ref({
  current: 1,
  size: 8,
  like: '',
  status: undefined as number | undefined,
  name: ''
})


// 搜索值
const searchVal = ref('')
const statusFilter = ref('showing')
// 展品列表数据
const exhibitionList = ref<ExhibitionItemVoduixiang[]>([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)
const isLoading = ref(true)

// 状态映射
const statusTextMap: Record<number, string> = {
  1: '展出中',
  2: '维护中',
  3: '已下架'
}

const statusValueMap: Record<string, number | undefined> = {
  all: undefined,
  showing: 1,
  maintenance: 2,
  removed: 3
}

// 获取状态类型
const getStatusType = (status: number) => {
  const typeMap: Record<number, string> = {
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return typeMap[status] || 'info'
}

// 空状态判断
const showEmpty = computed(() => {
  return exhibitionList.value.length === 0 && !isLoading.value
})

// 获取展品列表
const getExhibitionList = async () => {
  isLoading.value = true

  try {
    // 更新formData
    formData.value.current = currentPage.value
    formData.value.size = pageSize.value
    formData.value.name = searchVal.value
    formData.value.status = statusValueMap[statusFilter.value]

    const res = await scenicExhibitionItemPageUsingPost({
      body: formData.value
    })
    if (res.code === 0 && res.data) {
      exhibitionList.value = res.data.list || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取展品列表失败:', error)
    ElMessage.error('获取展品列表失败')
  } finally {
    isLoading.value = false
  }
}

// 搜索展品
const searchExhibitions = () => {
  currentPage.value = 1
  getExhibitionList()
}

// 状态筛选
const filterByStatus = () => {
  currentPage.value = 1
  getExhibitionList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getExhibitionList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getExhibitionList()
}

// 新增展品
const toAddExhibition = () => {
  router.push('/exhibition/edit')
}

// 编辑展品
const editExhibition = (item: ExhibitionItemVoduixiang) => {
  router.push(`/exhibition/edit?id=${item.id}`)
}

// 查看详情
const viewDetail = (item: ExhibitionItemVoduixiang) => {
  router.push(`/exhibition/detail?id=${item.id}`)
}

// 确认删除
const confirmDelete = (item: ExhibitionItemVoduixiang) => {
  ElMessageBox.confirm('确定要删除该展品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await scenicExhibitionItemOpenApiDeleteUsingPost({
            params: {
                id: item.id
            }
        })

        if (res.code === 0) {
          ElMessage.success('删除成功')
          getExhibitionList()
        } else {
          ElMessage.error(res.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除展品失败:', error)
        ElMessage.error('删除展品失败')
      }
    })
    .catch(() => {
      // 取消删除
    })
}

// 初始化
getExhibitionList()
</script>

<style lang="scss" scoped>
.exhibition-list {
  .exhibition-card {
    height: 100%;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-5px);
    }
    .action-buttons {
      display: flex;
      gap: 4px;

      .el-button {
        padding: 6px 8px;

        .el-icon {
          margin-right: 2px;
        }
      }
    }
  }
}
</style>